//
//  YSEmoticonKeyBoard.m
//  YSEmoticonKeyboard
//
//  Created by MOLBASE on 2017/12/21.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSEmoticonKeyBoard.h"
#import "UIImage+YSAdd.h"
#import "YSPageCollectionViewLayout.h"
#import "YSEmoticonCell.h"
#import "YSEmoticion.h"

static CGFloat const kTitleViewH = 44;
static NSString *const kEmoticonCellIdentifier = @"kEmoticonCellIdentifier";

@interface YSEmoticonKeyBoard () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) YSPageCollectionViewLayout *layout;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) UIView *titleView;
@property(nonatomic, strong) NSDictionary *emojiDict;

@end

@implementation YSEmoticonKeyBoard

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    self.backgroundColor = YSEmoticonRGB(246, 246, 246);
    
    [self addSubViews];
    [self layoutViews];
}

- (void)addSubViews {
    [self addSubview:self.collectionView];
    [self addSubview:self.pageControl];
    [self addSubview:self.titleView];
    
    [self.titleView addSubview:self.sendButton];
}

- (void)layoutViews {
    CGFloat pageControlH = 20;
    self.collectionView.frame = CGRectMake(0, 0, self.ys_width, self.ys_height - pageControlH - kTitleViewH);
    self.pageControl.frame = CGRectMake(0, self.collectionView.ys_bottom, self.ys_width, pageControlH);
    self.titleView.frame = CGRectMake(0, self.pageControl.ys_bottom, self.ys_width, kTitleViewH);
    
    CGFloat sendButtonW = 55;
    self.sendButton.frame = CGRectMake(self.titleView.ys_width - sendButtonW, 0, sendButtonW, self.titleView.ys_height);
}

#pragma mark - event response
- (void)sendButttonClick:(UIButton *)button {
    if ([self.delegate respondsToSelector:@selector(emoticonKeyBoard:clickSend:)]) {
        [self.delegate emoticonKeyBoard:self clickSend:self.sendButton];
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger itemCount = self.emojiDict.allKeys.count;
    NSInteger totalPage = (itemCount - 1) / (self.layout.rowCount * self.layout.columnCount - 1) + 1;
    
    if (section == 0) {
        self.pageControl.numberOfPages = totalPage;
    }
    return totalPage * (self.layout.rowCount * self.layout.columnCount);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YSEmoticonCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kEmoticonCellIdentifier forIndexPath:indexPath];
    NSInteger page = (indexPath.row+1) / (self.layout.rowCount * self.layout.columnCount);
    if ((indexPath.row + 1) % (self.layout.rowCount * self.layout.columnCount) == 0) {
        [cell setEmoticonImage:@"expression_delete"];
    } else {
        [cell setEmoticonImage:[NSString stringWithFormat:@"%zd", indexPath.row+1-page]];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger page = (indexPath.row+1) / (self.layout.rowCount * self.layout.columnCount);
    if ((indexPath.row + 1) % (self.layout.rowCount * self.layout.columnCount) == 0) {
        // delete
        NSLog(@"delete---");
        YSEmoticion *emoticion = [[YSEmoticion alloc] init];
        emoticion.type = YSEmoticionTypeDelete;
        if ([self.delegate respondsToSelector:@selector(emoticonKeyBoard:clickDelete:)]) {
            [self.delegate emoticonKeyBoard:self clickDelete:emoticion];
        }
    } else {
        // else
        NSString *imageStr = [NSString stringWithFormat:@"%zd", indexPath.row+1-page];
        if ([imageStr intValue] > self.emojiDict.count) {
            NSLog(@"space");
            return;
        } else {
            NSLog(@"%@", imageStr);
            YSEmoticion *emoticion = [[YSEmoticion alloc] init];
            emoticion.type = YSEmoticionTypeDefault;
            emoticion.emoticonImage = imageStr;
            emoticion.emoticonName = [self getKeyForValue:imageStr fromDict:self.emojiDict];
            if ([self.delegate respondsToSelector:@selector(emoticonKeyBoard:clickEmoticion:)]) {
                [self.delegate emoticonKeyBoard:self clickEmoticion:emoticion];
            }
        }
    }
}

- (NSString *)getKeyForValue:(NSString *)value fromDict:(NSDictionary *)dict {
    __block NSString *resultKey;
    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([obj isEqualToString:value]) {
            resultKey = key;
        }
    }];
    return resultKey;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewEndScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self scrollViewEndScroll];
    }
}

- (void)scrollViewEndScroll {
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:CGPointMake(self.layout.sectionInset.left + 1 + self.collectionView.contentOffset.x, self.layout.sectionInset.top + 1)];
    
    self.pageControl.currentPage = indexPath.item / (self.layout.columnCount * self.layout.rowCount);
}

#pragma mark - 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        YSPageCollectionViewLayout *layout = [[YSPageCollectionViewLayout alloc] init];
        self.layout = layout;
        layout.columnCount = 7;
        layout.rowCount = 3;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsVerticalScrollIndicator = false;
        _collectionView.showsHorizontalScrollIndicator = false;
        _collectionView.pagingEnabled = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[YSEmoticonCell class] forCellWithReuseIdentifier:kEmoticonCellIdentifier];
    }
    return _collectionView;
}

- (UIView *)titleView {
    if (!_titleView) {
        _titleView = [[UIView alloc] init];
        _titleView.backgroundColor = [UIColor whiteColor];
    }
    return _titleView;
}

- (UIButton *)sendButton {
    if (!_sendButton) {
        _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
        [_sendButton addTarget:self action:@selector(sendButttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_sendButton setBackgroundImage:[UIImage createImageWithColor:YSEmoticonRGB(0, 186, 255)] forState:UIControlStateNormal];
        
        [_sendButton setTitleColor:YSEmoticonRGB(143, 143, 143) forState:UIControlStateDisabled];
        [_sendButton setBackgroundImage:[UIImage createImageWithColor:YSEmoticonRGB(250, 250, 250)] forState:UIControlStateDisabled];
    }
    return _sendButton;
}

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
        _pageControl.hidesForSinglePage = YES;
        _pageControl.userInteractionEnabled = NO;
        _pageControl.numberOfPages = 4;
        _pageControl.currentPage = 0;
    }
    return _pageControl;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
        NSInteger itemCount = self.emojiDict.allKeys.count;
        NSInteger totalPage = (itemCount - 1) / (self.layout.rowCount * self.layout.columnCount - 1) + 1;
        NSInteger allCount = totalPage * (self.layout.rowCount * self.layout.columnCount);
        
        NSArray *emojiKeys = self.emojiDict.allKeys;
        for (int i = 0; i < allCount; i++) {
            YSEmoticion *emoticion = [[YSEmoticion alloc] init];
            if ((i + 1) % (self.layout.rowCount * self.layout.columnCount) == 0) {
                // 删除
                emoticion.emoticonImage = @"expression_delete";
                emoticion.type = YSEmoticionTypeDelete;
            } else if (i > itemCount + totalPage - 1) {
                // 空白
                emoticion.type = YSEmoticionTypeNone;
            } else {
                emoticion.emoticonName = emojiKeys[i];
                emoticion.emoticonImage = [self.emojiDict valueForKey:emojiKeys[i]];
                emoticion.type = YSEmoticionTypeDefault;
            }
            [_dataArray addObject:emoticion];
        }
        
    }
    return _dataArray;
}

- (NSDictionary *)emojiDict {
    if (!_emojiDict) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Emotions" ofType:@"plist"];
        _emojiDict = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    return _emojiDict;
}

@end
